﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing;//***  

namespace Blog_BLL
{
    /// <summary>
    /// 上传文件处理类
    /// </summary>
    public class Upload
    {
        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="uploadFileTypeP">上传文件类型</param>
        /// <param name="savePath">保存文件目录</param>
        /// <returns></returns>
        public static string UploadFile(HttpRequestBase _Request, UploadFileType uploadFileTypeP, string savePath)
        {
            string filePath = null;
            switch (uploadFileTypeP)
            {
                case UploadFileType.ImageType:
                    filePath = UploadFileImage(_Request, savePath);
                    break;
                case UploadFileType.ExeclType:
                    break;
                case UploadFileType.TxtType:
                    break;
            }
            return filePath;
        }
        private static string UploadFileImage(HttpRequestBase _Request, string savePath)
        {
            var file = _Request.Files[0]; //获取选中文件  
            Random ran = new Random((int)DateTime.Now.Ticks);//利用时间种子解决伪随机数短时间重复问题  
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ran.Next(99999) + file.FileName;
            string filePath = savePath + fileName;
            try
            {
                //判断是否存在文件目录
                if (!System.IO.Directory.Exists(savePath))
                    System.IO.Directory.CreateDirectory(savePath);
                //file.SaveAs(filePath);
                using (System.IO.FileStream fs = System.IO.File.Create(filePath))
                {
                    file.InputStream.CopyTo(fs);
                    fs.Flush();
                }
                return fileName;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
    public enum UploadFileType
    {
        /// <summary>
        /// 图片类型
        /// </summary>
        ImageType = 1,
        /// <summary>
        /// Execl类型
        /// </summary>
        ExeclType = 2,
        /// txt类型
        /// </summary>
        TxtType = 3
    }

}
